import { createStore, applyMiddleware, compose } from 'redux'
import Taro from '@tarojs/taro'
import thunkMiddleware from 'redux-thunk'
import { saveStorage } from '../actions/car'
import rootReducer from '../reducers'

const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
    // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
  })
  : compose

const middlewares = [
  thunkMiddleware
]

if (process.env.NODE_ENV === 'development') {
  middlewares.push(require('redux-logger').createLogger())
}

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares),
  // other store enhancers if any
)

export default function configStore() {
  const store = createStore(rootReducer, enhancer)

  // 订阅仓库： dispatch action 该回调函数会执行
  store.subscribe(() => {
    // 存储数据
    const state = store.getState();
    Taro.setStorageSync('carList', JSON.stringify(state.car.carList))
  })

  return store
}
